/**
 * Created by Administrator on 2017/6/1.
 */

//�طŵ�ַ
var PLAY_BACK_THE_ADDRESS ='';
//��Ƶ�����ַ
var VIDEO_RECORDING_ADDRESS = 'd:\\video';
var SINGLECAMERA=true;//�Ƿ��ǵ�����ͷ
var ISRECORDING=false;//�Ƿ�����¼��
var ISOPENPPT = true;//�Ƿ��PPT
var currentFileRole;

// ����ˮӡ����
var szJsonBuf4Txt = {
    fontcolor: "0x000000",
    alpha: 100,
    posx: 5,
    posy: 5,
    fontsize: 18,
    text: "[timestamp]"
};


//ͼƬˮӡ
var  szJsonBuf4Img = {
    alpha: 50, //ͼƬ͸���ȣ�Ĭ��Ϊ100���ɲ���������ʱ����Ӧ��Ĭ��ֵ��
    posx: 8, //ͼƬˮӡ��x�᷽���ϵ���ʼλ�ã��ٷֱȣ���Χ0~100����
    posy: 8, //ͼƬˮӡ��y�᷽���ϵ���ʼλ�ã��ٷֱȣ���Χ0~100����
    overlayimgwidth: 189, //��ͼƬ�Ŀ�ȣ��ɴ�0����ʾӦ��ͼƬ��ԭʼ��ȣ�������ֵʱ���鰴�߿�ȱ��������ã�
    overlayimgheight: 42, //ͼƬ�ĸ߶ȣ��ɴ�0����ʾӦ��ͼƬ��ԭʼ�߶ȣ�������ֵʱ���鰴�߿�ȱ��������ã�
    imagepath: "D:\\1.jpg" //ͼƬ��·��������ͼƬ�ı���·��������·������
};


//�򿪱�������ͷ����˷�
function local_open(){
    var mDevices = BRAC_EnumDevices(BRAC_DEVICE_VIDEOCAPTURE);
    console.log(mDevices);
    if(mDevices){
        for(var i=0;i<mDevices.length;i++){
            if(i>=1) continue;
            BRAC_SetUserStreamInfo(mSelfUserId, i, BRAC_STREAMINFO_VIDEOCODECID,mDevices[i]);
            VideoConfig(i);
            if(i == 0){
                BRAC_UserCameraControlEx(mSelfUserId,1,i,0,"");
                BRAC_UserSpeakControl(mSelfUserId,1);
                // BRAC_SetVideoPosEx(mSelfUserId, GetID("AnyChatRemoteVideoDiv"), "ANYCHAT_VIDEO_REMOTE", i);
                BRAC_SetVideoPosEx(mSelfUserId, GetID("AnyChatLocalVideoDiv"), "ANYCHAT_VIDEO_LOCAL", i);
            }else{
                BRAC_UserCameraControlEx(mSelfUserId,1,i,0,"");
                BRAC_SetVideoPosEx(mSelfUserId, GetID("AnyChatLocalVideoDiv"), "ANYCHAT_VIDEO_LOCAL", i);
            }
        }

        if(mDevices.length==1){
            SINGLECAMERA = true;
            rec_tag =  BRAC_RECORD_FLAGS_VIDEO + BRAC_RECORD_FLAGS_AUDIO + BRAC_RECORD_FLAGS_MIXAUDIO + BRAC_RECORD_FLAGS_MIXVIDEO +BRAC_RECORD_FLAGS_STEREO+BRAC_RECORD_FLAGS_LOCALCB;
            $('#switchover').hide();


        }else{
            setTimeout(function(){
                AnyChatRemoteVideoDiv(true);
            },1000);

            SINGLECAMERA = false;
        }
    }

    function VideoConfig(dwStreamIndex){
        // ���ñ�����Ƶ��������ʣ��������Ϊ0�����ʾʹ����������ģʽ��
        BRAC_SetUserStreamInfo(-1,dwStreamIndex,BRAC_SO_LOCALVIDEO_BITRATECTRL,400000);

        // ���ñ�����Ƶ���������
        BRAC_SetUserStreamInfo(-1,dwStreamIndex,BRAC_SO_LOCALVIDEO_QUALITYCTRL,3);

        // ���ñ�����Ƶ�ɼ��ֱ���
        BRAC_SetUserStreamInfo(-1,dwStreamIndex,BRAC_SO_LOCALVIDEO_WIDTHCTRL, 640);
        BRAC_SetUserStreamInfo(-1,dwStreamIndex,BRAC_SO_LOCALVIDEO_HEIGHTCTRL, 480);

        // ���ñ�����Ƶ�����֡��
        BRAC_SetUserStreamInfo(-1,dwStreamIndex,BRAC_SO_LOCALVIDEO_FPSCTRL,15);
        // ���ñ�����Ƶ����Ĺؼ�֡���
        BRAC_SetUserStreamInfo(-1,dwStreamIndex,BRAC_SO_LOCALVIDEO_GOPCTRL, 30);
        // ������Ƶ����Ԥ�������ֵԽ�󣬱�������Խ�ߣ�ռ��CPU��ԴҲ��Խ�ߣ�
        BRAC_SetUserStreamInfo(-1,dwStreamIndex,BRAC_SO_LOCALVIDEO_PRESETCTRL,3);
        // ����Ƶ������Ч
        BRAC_SetUserStreamInfo(-1,dwStreamIndex,BRAC_SO_LOCALVIDEO_APPLYPARAM,1);
    }

    mRefreshVolumeTimer = setInterval(function () {
        GetID("LocalAudioVolume").style.width = GetID("AnyChatLocalVideoDiv").offsetHeight * BRAC_QueryUserStateInt(mSelfUserId, BRAC_USERSTATE_SPEAKVOLUME) / 100 + "px";
    }, 100);
}


var video_fuc = (function(){
    var recording = true;
    var fileadd = VIDEO_RECORDING_ADDRESS;//����¼���ļ��ĵ�ַ
    var func = {};
    var string = {};
    $('#playback').css("display","none");
    $("#fileUpload").css("display","none");
    //��Ƶ¼��
    $('#recording').click(function(){
        var dwFlags;
        if(recording){
            dwFlags = 1;
            ISRECORDING = true;
            var countDown = 4;
            $(this).text('����¼��('+countDown+')').addClass('btn-danger');
            $(this).attr("disabled",true);
            var _this=$(this);
            var tRecord = setInterval(function(){
                countDown = countDown - 1;
                _this.text('����¼��('+countDown+')');
                if(countDown == 0){
                    _this.text('����¼��');
                    _this.removeAttr("disabled");
                    clearInterval(tRecord);
                }
            }, 1000);

        }else{
            dwFlags = 0;
            ISRECORDING = false;
            $(this).text('��ʼ¼��').removeClass('btn-danger');
        }

        //  BRAC_SO_RECORD_TMPDIR

        string = {
            "recordlayout":2,
            "streamlist":[
                {
                    "userid":-1,
                    "streamindex":0,
                    "recordindex":0
                },
                {
                    "userid":-1,
                    "streamindex":1,
                    "recordindex":1
                }
            ],
            //"textoverlay": szJsonBuf4Txt
            "watermark":szJsonBuf4Img
        };

        rec_tag = BRAC_RECORD_FLAGS_VIDEO + BRAC_RECORD_FLAGS_AUDIO + BRAC_RECORD_FLAGS_MIXAUDIO + BRAC_RECORD_FLAGS_MIXVIDEO + BRAC_RECORD_FLAGS_STEREO + BRAC_RECORD_FLAGS_LOCALCB+BRAC_RECORD_FLAGS_ABREAST;
        BRAC_StreamRecordCtrlEx(-1,dwFlags,0x1b33, 0,JSON.stringify(string));
        if(recording)currentMediaPlayer.once_img();
        recording = !recording;
    });

    //��Ƶ�ط�
    $('#playback').click(function(){
        if(currentFileRole!=undefined){
            //�������ſ�
            $("#videotag").show();

            var szUrl = BRAC_GetSDKOptionStringEx(BRAC_SO_LOCALPATH2URL, currentFileRole, 0);//���ص�ַת�������ַ
            //Mp4Player(szUrl);
            Mp4Player(currentFileRole);
        }


    });
    //���ŵ���ر�
    $("#backPlay").click(function() {
        $("#videotag").hide();
        recordMediaPlayer.destroy();
    });
    //���ŵ���ر�
    $("#icon").click(function() {
        $("#videotag").hide();
        recordMediaPlayer.destroy();
    });

    //�ļ��ϴ�
    $("#fileUpload").click(function(){
        if(currentFileRole!=undefined){
            TaskGuid = BRAC_GetSDKOptionString(BRAC_SO_CORESDK_NEWGUID);
            // BRAC_TransFile(0, currentFileRole,0,0,0);
            BRAC_TransFileEx(TaskGuid, 0, currentFileRole, 0, "");
            $("#fileUpload").attr("disabled","true");
            $("#fileUpload").text("�ϴ���...");
            $("#file_Upload").show();
            //��ѯ�ϴ��������
            queryAllTransTasks();
        }

    });
    //�ļ��ϴ�����ر�
    $("#file_Upload_icon").click(function() {
        $("#file_Upload").hide();
    });


    return func;
})();

// ��ѯ�ϴ��������
function queryAllTransTasks() {
    var t = setInterval(function() {

        var status = BRAC_QueryTransTaskInfoEx(TaskGuid, BRAC_TRANSTASK_PROGRESS);
        console.info(status);
        $("#file_Upload .bar").css("width",status + "%");
        $("#file_Upload .bar").text(status + "%");
        if(status==100){
            clearInterval(t);
            $("#file_Upload").hide();
        }

    }, 1000);
}
//�ļ��ϴ����
function file_upload_callback(lpFileName,lpTempFilePath) {
    console.info("�ϴ��ɹ�"+lpFileName);
    $("#fileUpload").removeAttr("disabled");
    $("#fileUpload").text("�ļ��ϴ�")
}
//¼��ɹ�
function recordCallback(url) {
    currentFileRole=url;
    $('#playback').css("display","inline-block");
    $("#fileUpload").css("display","inline-block");
}


var record_play_ing = false;         //ý���Ƿ����ڲ���
var recordMediaPlayer;
var exitFullscreenTimer;
var recordPlayer = (function(){
    var $mediaView_process =  $('#mediaView_process');
    var $play_time = $('#recordPlayTime');
    var fuc = {};

    var $play_auto_ppt = $('#playBtn'); //���Ű�ť
    var $play_stop=$('#stopBtn');                //ֹͣ��ť
    var is_play = false;                      //�Ƿ񲥷Ż���ͣ

    var recordPlayStatusTimer;                     //��ǰ����״̬�Ķ�ʱ��

    var recordDragBtn =$("dragProgressBtn");
    var videoDuration;                             //��Ƶʱ��

    $play_stop.hide();
    $play_stop.attr("disabled","true");

    function record_player_init(url){


        recordMediaPlayer = new AnyChatMediaUtils.Player({
            filepath:url,
            viewid:"videotagMp4",
            streamindex:2,
            playendcallback:function(resultJson){
                /**
                 *���Żص�
                 *yourcode
                 */
                play_show_status(false);
                console.log("�������");
                console.dir(resultJson);

            }
        });

        if(record_play_ing){
            show_player_status(false);
        }


        $(".video_play_wrapper .loading-icon").show();


        if(recordPlayStatusTimer){
            recordMediaPlayer.stop();
            clearInterval(recordPlayStatusTimer);
        }

        recordPlayStatusTimer = setInterval(function(){
            show_player_status(); //��ȡ����״̬
        },1000)

    }

    /**
     * ���Ž�����ʾ
     */
    function show_player_status(){
        var json = recordMediaPlayer.getPlayStatus();
        if(json){
            videoDuration = json.audioduration;
            var playTime = json.playtime;
            var process = playTime/videoDuration;
            $("#recordPlayProcess").css('width',process*100+'%');
            $("#recordPlayTime").text(formatSeconds (~~(playTime/1000))+' / '+ formatSeconds(Math.ceil(videoDuration/1000)));
        }
        $(".video_play_wrapper .loading-icon").hide();
    }


    function play_show_status(is){
        if(is){
            $('#page-left').hide();
            $('#page-right').hide();
            $play_auto_ppt.addClass('btn_pause');
           // $play_stop.show();
            record_play_ing = true;
            is_play = true;
        }else{
            $play_auto_ppt.removeClass('btn_pause');
           // $play_stop.hide();
            record_play_ing = false;
            is_play = false;
        }
        if(is_play){
            recordPlayStatusTimer = setInterval(function(){
                show_player_status(); //��ȡ����״̬
            },1000)
        }else{
            clearInterval(recordPlayStatusTimer);
        }
    }

    /**
     * ֹͣ����
     */
    $play_stop.click(function(){
        recordMediaPlayer.stop();
        play_show_status(false);
        $play_stop.attr("disabled","true");
    });

    /**
     * ���Ż���ͣ
     */
    $play_auto_ppt.click(function(){
        if(!is_play){
            //����
            recordMediaPlayer.play();
            play_show_status(true);

            //��ʾֹͣ��ť
            $play_stop.removeAttr("disabled");
        }else{
            //��ͣ
            recordMediaPlayer.pause();
            play_show_status(false);
            //��ʾֹͣ��ť
            $play_stop.attr("disabled","true");
        }
    });

    /**
     * ���Ž����϶�
     */
    var recordDrag = new Drag("dragProgressBtn");
    function Drag(id) {
        this.div = document.getElementById(id);
        if (this.div) {
            this.div.style.position = "absolute";
        }
        this.disX = 0;
        this.currentDistance = 0;
        var _this = this;
        this.div.onmousedown = function (evt) {
            recordMediaPlayer.pause();
           play_show_status(false);
            //clearInterval(recordPlayStatusTimer);
            _this.getDistance(evt);
            document.onmousemove = function (evt) {
                _this.currentDistance = _this.setPosition(evt);
                console.log(evt);
            };
            //_this.div.onmouseup = function () {
            //    _this.clearEvent();
            //};
            document.onmouseup = function () {
                _this.clearEvent();
            }
        }
    }
    Drag.prototype.getDistance = function (evt) {
        var oEvent = evt || event;
        this.disX = oEvent.clientX - this.div.offsetLeft;
    };
    Drag.prototype.setPosition = function (evt) {
        var oEvent = evt || event;
        var leftDistance = oEvent.clientX - this.disX;
        if (leftDistance <= 0) {
            leftDistance = 0;
        }
        else if (leftDistance >= document.documentElement.clientWidth - this.div.offsetWidth) {
            leftDistance = document.documentElement.clientWidth - this.div.offsetWidth;
        }
        return leftDistance;
    };
    Drag.prototype.clearEvent = function () {
        //this.div.onmouseup = null;
        getCurrentPlayTime();
        document.onmousemove = null;
        document.onmouseup = null;
    };

    function getCurrentPlayTime(){
        var dragDistance= recordDrag.currentDistance;
        //document.getElementById("dragProgressBtn").style.left = dragDistance + "px";
        //document.getElementById("dragProgressBtn").parentNode.style.width=dragDistance + "px";
        var totalWidth = document.getElementsByClassName('jAudio--progress-bar-wrapper')[0].clientWidth;

        var percent = dragDistance/ totalWidth;

        var currentTime = (videoDuration * percent)/1000;
        $("#recordPlayProcess").css('width',percent*100+'%');
        $("#recordPlayTime").text(formatSeconds (~~(currentTime/1000))+' / '+ formatSeconds(Math.ceil(videoDuration/1000)));
        recordMediaPlayer.dragProcess(currentTime);
        recordPlayStatusTimer = setInterval(function(){
            show_player_status(); //��ȡ����״̬
        },1000)

        console.log(dragDistance);
        console.log(totalWidth);
        console.log(videoDuration);
        console.log(percent);
        console.log(currentTime);
    }
    /*
    * ȫ��ģʽ�����л�
    */
    //�ж��Ƿ�ȫ��ģʽ
    var invokeFieldOrMethod = function(element, method)
    {
        var usablePrefixMethod;
        ["webkit", "moz", "ms", "o", ""].forEach(function(prefix) {
            if (usablePrefixMethod) return;
            if (prefix === "") {
                method = method.slice(0,1).toLowerCase() + method.slice(1);
            }
            var typePrefixMethod = typeof element[prefix + method];
            if (typePrefixMethod + "" !== "undefined") {
                if (typePrefixMethod === "function") {
                    usablePrefixMethod = element[prefix + method]();
                } else {
                    usablePrefixMethod = element[prefix + method];
                }
            }
        });

        return usablePrefixMethod;
    };

    //����ȫ��
    function launchFullscreen(element)
    {
        //�˷�����������?����?��?�У���?���?��ȫ��
        if(element.requestFullscreen) {
            element.requestFullscreen();
        } else if(element.mozRequestFullScreen) {
            element.mozRequestFullScreen();
        } else if(element.msRequestFullscreen){
            element.msRequestFullscreen();
        } else if(element.oRequestFullscreen){
            element.oRequestFullscreen();
        }
        else if(element.webkitRequestFullscreen)
        {
            element.webkitRequestFullScreen();
        }else{

            var docHtml  = document.documentElement;
            var docBody  = document.body;
            var videobox  = document.getElementById('video_play_wrapper');
            var  cssText = 'width:100%;height:100%;overflow:hidden;';
            docHtml.style.cssText = cssText;
            docBody.style.cssText = cssText;
            videobox.style.cssText = cssText+';'+'margin:0px;padding:0px;';
            document.IsFullScreen = true;

        }

        var newHeight = window.screen.availWidth *(3/(4*2));
        document.getElementById('videotagMp4').style.cssText ='width:100%; height:' + newHeight +'px; margin-top:' + (window.screen.availHeight-newHeight)/2 + 'px;';
    }
    //�˳�ȫ��
    function exitFullscreen()
    {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if(document.oRequestFullscreen){
            document.oCancelFullScreen();
        }else if (document.webkitExitFullscreen){
            document.webkitExitFullscreen();
        }else{
            var docHtml  = document.documentElement;
            var docBody  = document.body;
            var videobox  = document.getElementById('video_play_wrapper');
            docHtml.style.cssText = "";
            docBody.style.cssText = "";
            videobox.style.cssText = "";
            document.IsFullScreen = false;
        }
        document.getElementById('videotagMp4').style.cssText ='';
    }
    document.getElementById('fullscreenBtn').addEventListener('click',function(){
        var btnclass = document.getElementById('fullscreenBtn').className;
        if( btnclass =="btn btn_exitfullscreen"){
            document.getElementById('fullscreenBtn').className="btn btn_fullscreen";
        }else{
            document.getElementById('fullscreenBtn').className="btn btn_exitfullscreen";
        }
        launchFullscreen(document.getElementById('video_play_wrapper'));
        //���������Ƿ���ȫ��
        if(invokeFieldOrMethod(document,'FullScreen') || invokeFieldOrMethod(document,'IsFullScreen') || document.IsFullScreen)
        {
            exitFullscreen();
        }

        /*
        * ���������Ƿ���ȫ����ESC��ť������
        */
        exitFullscreenTimer = setInterval(function(){
            //���������Ƿ���ȫ��
            if(recordPlayer.invokeFieldOrMethod(document,'FullScreen') || recordPlayer.invokeFieldOrMethod(document,'IsFullScreen') || document.IsFullScreen)
            {
            }else{
                recordPlayer.exitFullscreen();
                document.getElementById('fullscreenBtn').className="btn btn_fullscreen";
                clearInterval(exitFullscreenTimer);
            }
        },1000);

    },false);



    fuc.show_player_status = show_player_status;
    fuc.record_player_init = record_player_init;
    fuc.invokeFieldOrMethod = invokeFieldOrMethod;
    fuc.exitFullscreen = exitFullscreen;
    return fuc;

})();


//���ŵ�ַ����
function Mp4Player(mp4){
    recordPlayer.record_player_init(mp4);
}


function OnFullscreen(el){
    console.info(  el.offsetWidth , screen.width )
    if(el.clientWidth== screen.width){
        $("#video_overlay").show();
    }else{
        $("#video_overlay").hide();
    }

}

